package com.ruoyi.project.qiChe.kongZhi.controller;

import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.framework.aspectj.lang.annotation.Log;
import com.ruoyi.framework.aspectj.lang.enums.BusinessType;
import com.ruoyi.framework.config.RuoYiConfig;
import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.framework.web.domain.Ztree;
import com.ruoyi.project.qiChe.kongZhi.domain.KongZhi;
import com.ruoyi.project.qiChe.kongZhi.service.IKongZhiService;
import com.ruoyi.project.system.role.domain.Role;
import com.ruoyi.project.system.user.domain.User;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * 部门信息
 * 
 * @author ruoyi
 */
@Controller
@RequestMapping("/qiChe/kongZhi")
public class KongZhiController extends BaseController
{
    private String prefix = "qiChe/kongZhi";

    @Autowired
    private IKongZhiService kongZhiService;

    @RequiresPermissions("qiChe:kongZhi:view")
    @GetMapping()
    public String kongZhi()
    {
        return prefix + "/list";
    }

    @RequiresPermissions("qiChe:kongZhi:list")
    @PostMapping("/list")
    @ResponseBody
    public List<KongZhi> jlist(KongZhi kongZhi)
    {
        List<KongZhi> deptList = kongZhiService.selectDeptList(kongZhi);
        return deptList;
    }

    /**
     * 新增部门
     */
    @GetMapping("/add/{parentId}")
    public String add(@PathVariable("parentId") Long parentId, ModelMap mmap)
    {
        mmap.put("kongZhi", kongZhiService.selectDeptById(parentId));
        return prefix + "/add";
    }





    /**
     * 新增保存部门
     */
    @Log(title = "控制管理", businessType = BusinessType.INSERT)
    @RequiresPermissions("qiChe:kongZhi:add")
    @PostMapping("/add")
    @ResponseBody
    //public AjaxResult addSave(@Validated KongZhi kongZhi, HttpServletRequest request, HttpServletResponse response) throws Exception {
    public AjaxResult addSave(@Validated KongZhi kongZhi) throws Exception {
        if (UserConstants.DEPT_NAME_NOT_UNIQUE.equals(kongZhiService.checkDeptNameUnique(kongZhi)))
        {
            return error("新增控制'" + kongZhi.getDeptName() + "'失败，控制名称已存在");
        }
        if (!kongZhi.getTuBiaoFile().isEmpty()) {
            String tuBiaoLuJing = FileUploadUtils.upload(kongZhi.getTuBiaoFile());
            kongZhi.setTuBiaoLuJing(tuBiaoLuJing);
        }else{
            kongZhi.setTuBiaoLuJing("/img/mo_ren1.png");
        }

//        if (!kongZhi.getTuBiaoDianJiFile().isEmpty()) {
//            String tuBiaoDianJiLuJing = FileUploadUtils.upload(kongZhi.getTuBiaoDianJiFile());
//            kongZhi.setTuBiaoDianJiLuJing(tuBiaoDianJiLuJing);
//        }else{
//            kongZhi.setTuBiaoDianJiLuJing("/img/mo_ren2.png");
//        }

        return toAjax(kongZhiService.insertDept(kongZhi));
    }

    /**
     * 修改
     */
    @GetMapping("/edit/{deptId}")
    public String edit(@PathVariable("deptId") Long deptId, ModelMap mmap)
    {
        KongZhi kongZhi = kongZhiService.selectDeptById(deptId);
        if (StringUtils.isNotNull(kongZhi) && 100L == deptId)
        {
            kongZhi.setParentName("无");
        }
        mmap.put("kongZhi", kongZhi);
        return prefix + "/edit";
    }

    /**
     * 保存
     */
    @Log(title = "部门管理", businessType = BusinessType.UPDATE)
    @RequiresPermissions("qiChe:kongZhi:edit")
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(@Validated KongZhi kongZhi) throws IOException {


        if (UserConstants.DEPT_NAME_NOT_UNIQUE.equals(kongZhiService.checkDeptNameUnique(kongZhi)))
        {
            return error("修改控制'" + kongZhi.getDeptName() + "'失败，控制名称已存在");
        }
        else if (kongZhi.getParentId().equals(kongZhi.getDeptId()))
        {
            return error("修改控制'" + kongZhi.getDeptName() + "'失败，上级控制不能是自己");
        }
        else if (StringUtils.equals(UserConstants.DEPT_DISABLE, kongZhi.getStatus())
                && kongZhiService.selectNormalChildrenDeptById(kongZhi.getDeptId()) > 0)
        {
            return AjaxResult.error("该控制包含未停用的子控制！");
        }

        if (!kongZhi.getTuBiaoFile().isEmpty()) {
            String tuBiaoLuJing = FileUploadUtils.upload(kongZhi.getTuBiaoFile());
            kongZhi.setTuBiaoLuJing(tuBiaoLuJing);
        }else{
            kongZhi.setTuBiaoLuJing("/img/mo_ren1.png");
        }

//        if (!kongZhi.getTuBiaoDianJiFile().isEmpty()) {
//            String tuBiaoDianJiLuJing = FileUploadUtils.upload(kongZhi.getTuBiaoDianJiFile());
//            kongZhi.setTuBiaoDianJiLuJing(tuBiaoDianJiLuJing);
//        }

        return toAjax(kongZhiService.updateDept(kongZhi));
    }

    /**
     * 删除
     */
    @Log(title = "部门管理", businessType = BusinessType.DELETE)
    @RequiresPermissions("qiChe:kongZhi:remove")
    @GetMapping("/remove/{deptId}")
    @ResponseBody
    public AjaxResult remove(@PathVariable("deptId") Long deptId)
    {
        if (kongZhiService.selectDeptCount(deptId) > 0)
        {
            return AjaxResult.warn("存在下级控制功能,不允许删除");
        }
        /*
        if (kongZhiService.checkDeptExistUser(deptId))
        {
            return AjaxResult.warn("部门存在用户,不允许删除");
        }
         */
        return toAjax(kongZhiService.deleteDeptById(deptId));
    }

    /**
     * 校验部门名称
     */
    @PostMapping("/checkDeptNameUnique")
    @ResponseBody
    public String checkDeptNameUnique(KongZhi kongZhi)
    {
        return kongZhiService.checkDeptNameUnique(kongZhi);
    }

    /**
     * 选择部门树
     * 
     * @param deptId 部门ID
     * @param excludeId 排除ID
     */
    @GetMapping(value = { "/selectDeptTree/{deptId}", "/selectDeptTree/{deptId}/{excludeId}" })
    public String selectDeptTree(@PathVariable("deptId") Long deptId,
            @PathVariable(value = "excludeId", required = false) String excludeId, ModelMap mmap)
    {
        mmap.put("kongZhi", kongZhiService.selectDeptById(deptId));
        mmap.put("excludeId", excludeId);
        return prefix + "/tree";
    }

    /**
     * 加载部门列表树
     */
    @GetMapping("/treeData")
    @ResponseBody
    public List<Ztree> treeData()
    {
        List<Ztree> ztrees = kongZhiService.selectDeptTree(new KongZhi());
        return ztrees;
    }

    /**
     * 加载部门列表树（排除下级）
     */
    @GetMapping("/treeData/{excludeId}")
    @ResponseBody
    public List<Ztree> treeDataExcludeChild(@PathVariable(value = "excludeId", required = false) Long excludeId)
    {
        KongZhi kongZhi = new KongZhi();
        kongZhi.setDeptId(excludeId);
        List<Ztree> ztrees = kongZhiService.selectDeptTreeExcludeChild(kongZhi);
        return ztrees;
    }

    /**
     * 加载角色部门（数据权限）列表树
     */
    @GetMapping("/roleDeptTreeData")
    @ResponseBody
    public List<Ztree> deptTreeData(Role role)
    {
        List<Ztree> ztrees = kongZhiService.roleDeptTreeData(role);
        return ztrees;
    }
}
